package com.bomb.common.file;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 使用Executors.newFixedThreadPool和callable 多线程的另外一种实现,<br>
 * 获取文件目录下所有的文件总大小
 * ---此方法需要优化线程池的数量
 * @className NaivelyConcurrentTotalFileSize
 * @date 2015年8月31日 下午2:56:51
 * @author <a href="mailto:waferslove@sina.com">王星火</a>
 * @version V1.0
 */
public class NaivelyConcurrentTotalFileSize {
	
	private long getTotalSizeOfFilesInDir(final ExecutorService service, File file)
			throws InterruptedException, ExecutionException, TimeoutException {
		// 如果是文件，返回文件的大小
		if (file.isFile())
			return file.length();
		long total = 0;
		File[] children = file.listFiles();
		if (children != null) {
			List<Future<Long>> partialTotalFutures = new ArrayList<Future<Long>>();
			for (final File child : children) {
				partialTotalFutures.add(service.submit(new Callable<Long>() {
					public Long call() throws InterruptedException,
							ExecutionException, TimeoutException {
						return getTotalSizeOfFilesInDir(service, child);
					}
				}));
			}
			for (Future<Long> partialTotalFuture : partialTotalFutures)
				total += partialTotalFuture.get(100, TimeUnit.SECONDS);
		}
		return total;
	}

	public long getTotalSizeOfFile(File file)
			throws InterruptedException, ExecutionException, TimeoutException {
		ExecutorService service = Executors.newFixedThreadPool(1000);
		try {
			return getTotalSizeOfFilesInDir(service, file);
		} finally {
			service.shutdown();
		}
	}

}
